package de.mhus.lib.mandala.form;

import de.mhus.lib.mandala.AbstractComponent;
import de.mhus.lib.mandala.Component;
import de.mhus.lib.mandala.Response;
import de.mhus.lib.mandala.TagAttributes;
import de.mhus.lib.mandala.attributes.NamedAttribute;
import de.mhus.lib.mandala.attributes.NegativeBooleanAttribute;
import de.mhus.lib.mandala.text.Text;

public abstract class FormInput extends AbstractComponent {

	private String id;
	private String placeHolder = "";

	public FormInput(String id, String caption) {
		super(caption);
		setId(id);
	}
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
		getTagAttributes().setBindValue(new NamedAttribute(id));
	}

	public String getPlaceHolder() {
		return placeHolder;
	}

	public void setPlaceHolder(String placeHolder) {
		this.placeHolder = placeHolder;
	}

	@Override
	protected void doRender(Response out) {
		
		out.startTag("div", "form-group", null);
		out.startTag("label", "col-sm-2 control-label", null, "for", getId());
		getCaption().doRender(this, out);
		out.endTag("label");
		out.startTag("div", "col-sm-10", null);
		doRenderInput(out);
		out.endTag("div");
		out.endTag("div");

	}
	
	protected void doRenderInput(Response out) {
		if (getParent() != null && getParent() instanceof Form) {
			switch (((Form)getParent()).getMode()) {
			case READ:
				doRenderView(out);
				break;
			case WRITE:
				doRenderEdit(out);
				break;
			case READWRITE:
				TagAttributes viewTag = new TagAttributes();
				viewTag.setBindVisible(new NegativeBooleanAttribute(((Form)getParent()).getEditableSwitch()));
				out.startTag("div", null, viewTag);
				doRenderView(out);
				out.endTag("div");
				TagAttributes editTag = new TagAttributes();
				editTag.setBindVisible(((Form)getParent()).getEditableSwitch());
				out.startTag("div", null, editTag);
				doRenderEdit(out);
				out.endTag("div");
				break;
			}
		} else
			doRenderEdit(out);
	}

	protected abstract void doRenderEdit(Response out);

	protected abstract void doRenderView(Response out);
	
}
